package com.zzedu.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import com.zzedu.common.annotation.Log;
import com.zzedu.common.core.controller.BaseController;
import com.zzedu.common.core.domain.AjaxResult;
import com.zzedu.common.core.domain.entity.SysUser;
import com.zzedu.common.core.page.TableDataInfo;
import com.zzedu.common.enums.BusinessType;
import com.zzedu.common.enums.UserTypeEnumns;
import com.zzedu.common.utils.SecurityUtils;
import com.zzedu.common.utils.ServletUtils;
import com.zzedu.common.utils.StringUtils;
import com.zzedu.common.utils.bean.BeanUtils;
import com.zzedu.common.utils.poi.ExcelUtil;
import com.zzedu.domain.ZzTeacher;
import com.zzedu.dto.ZzTeacherDTO;
import com.zzedu.enmuns.ConfigEnums;
import com.zzedu.framework.web.service.SysPasswordService;
import com.zzedu.service.IZzTeacherService;
import com.zzedu.system.service.ISysConfigService;
import com.zzedu.vo.ZzTeacherVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 教师管理Controller
 *
 * @author Mr.Wang
 * @date 2025-02-16
 */
@RestController
@RequestMapping("/school/teacher")
public class ZzTeacherController extends BaseController {
    @Autowired
    private IZzTeacherService zzTeacherService;
    @Autowired
    ISysConfigService sysConfigService;

    @Autowired
    SysPasswordService passwordService;

    /**
     * 查询教师管理列表
     */
    @PreAuthorize("@permission.hasAnyPermissions('school:teacher:query')")
    @RequestMapping("/list")
    public TableDataInfo list(@RequestBody ZzTeacherDTO zzTeacher) {
        IPage<ZzTeacher> page = zzTeacherService.page(zzTeacher.getPageDTO(), zzTeacherService.buildQuery(zzTeacher));

        return getDataTable(page, zzTeacherService.convertVO(page.getRecords()));
    }

    /**
     * 导出教师管理列表
     */
    @PreAuthorize("@permission.hasAnyPermissions('school:teacher:export')")
    @Log(title = "教师管理", businessType = BusinessType.EXPORT)
    @RequestMapping("/export")
    public void export(ZzTeacherDTO zzTeacher) {
        List<ZzTeacher> list = zzTeacherService.list(zzTeacherService.buildQuery(zzTeacher));
        ExcelUtil<ZzTeacherVO> util = new ExcelUtil<ZzTeacherVO>(ZzTeacherVO.class);
        util.exportExcel(ServletUtils.getResponse(), zzTeacherService.convertVO(list), "教师管理数据");
    }


    /**
     * 新增保存教师管理
     */
    @PreAuthorize("@permission.hasAnyPermissions('school:teacher:add')")
    @Log(title = "教师管理", businessType = BusinessType.INSERT)
    @RequestMapping("/add")
    public AjaxResult addSave(@Validated @RequestBody ZzTeacherDTO zzTeacherDTO) {
        ZzTeacher zzTeacher = new ZzTeacher();

        BeanUtils.copyBeanProp(zzTeacher, zzTeacherDTO);
        String[] provinceAndCityAndDistrict = zzTeacherDTO.getProvinceAndCityAndDistrict();
        if (null != provinceAndCityAndDistrict && provinceAndCityAndDistrict.length > 0) {
            zzTeacher.setProvince(provinceAndCityAndDistrict[0]);
            if (provinceAndCityAndDistrict.length > 1) {
                zzTeacher.setCity(provinceAndCityAndDistrict[1]);
            }
            if (provinceAndCityAndDistrict.length > 2) {
                zzTeacher.setDistrict(provinceAndCityAndDistrict[2]);
            }
        }
        if (!StringUtils.isNotBlank(zzTeacher.getPwd())) {
            zzTeacher.setPwd(sysConfigService.selectConfigByKey(ConfigEnums.SYS_USER_INITPASSWORD.getCode()));
        }
        zzTeacher.setTel(StringUtils.trimToEmpty(zzTeacher.getTel()));
        SysUser sysUser = SecurityUtils.getSysUser();
        UserTypeEnumns useType = UserTypeEnumns.getCode(sysUser.getUserType());
        if (UserTypeEnumns.SCHOOL == useType) {
            zzTeacher.setSchoolId(sysUser.getUserTypeId());
        }
        if (StringUtils.isNotBlank(zzTeacher.getPwd())) {
            zzTeacher.setPwd(passwordService.encryptPassword(zzTeacher.getPwd()));
        }
        return toAjax(zzTeacherService.save(zzTeacher));
    }


    /**
     * 获取教师管理详细信息
     */
    @PreAuthorize("@permission.hasAnyPermissions('school:teacher:query')")
    @RequestMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        ZzTeacherVO zzTeacherVO = zzTeacherService.convertVO(Lists.newArrayList(zzTeacherService.getById(id))).get(0);
        JSONObject jsonObject = (JSONObject) JSON.toJSON(zzTeacherVO);
        jsonObject.put("provinceAndCityAndDistrict", Lists.newArrayList(zzTeacherVO.getProvince(), zzTeacherVO.getCity(), zzTeacherVO.getDistrict()));
        return success(
                jsonObject
        );
    }


    /**
     * 修改保存教师管理
     */
    @PreAuthorize("@permission.hasAnyPermissions('school:teacher:edit')")
    @Log(title = "教师管理", businessType = BusinessType.UPDATE)
    @RequestMapping("/edit")
    public AjaxResult editSave(@Validated @RequestBody ZzTeacherDTO zzTeacherDTO) {
        ZzTeacher zzTeacher = new ZzTeacher();
        BeanUtils.copyBeanProp(zzTeacher, zzTeacherDTO);
        String[] provinceAndCityAndDistrict = zzTeacherDTO.getProvinceAndCityAndDistrict();
        if (null != provinceAndCityAndDistrict && provinceAndCityAndDistrict.length > 0) {
            zzTeacher.setProvince(provinceAndCityAndDistrict[0]);
            if (provinceAndCityAndDistrict.length > 1) {
                zzTeacher.setCity(provinceAndCityAndDistrict[1]);
            }
            if (provinceAndCityAndDistrict.length > 2) {
                zzTeacher.setDistrict(provinceAndCityAndDistrict[2]);
            }
        }
        if (!StringUtils.isNotBlank(zzTeacher.getPwd())) {
            zzTeacher.setPwd(sysConfigService.selectConfigByKey(ConfigEnums.SYS_USER_INITPASSWORD.getCode()));
        }
        zzTeacher.setTel(StringUtils.trimToEmpty(zzTeacher.getTel()));
        zzTeacher.setSchoolId(null);
        if (StringUtils.isNotBlank(zzTeacher.getPwd())) {
            zzTeacher.setPwd(passwordService.encryptPassword(zzTeacher.getPwd()));
        }
        return toAjax(zzTeacherService.updateById(zzTeacher));
    }

    /**
     * 删除教师管理
     */
    @PreAuthorize("@permission.hasAnyPermissions('school:teacher:remove')")
    @Log(title = "教师管理", businessType = BusinessType.DELETE)
    @RequestMapping("/remove/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        return toAjax(zzTeacherService.removeBatchByIds(ids));
    }
}
